﻿using Ldt.DataEngine.DataFlowParse;
using Ldt.DataEngine.LogHandle;
using Ldt.SettingCenter.Core;
using LDT.Task.JudgetDoc.Generation.DataBase;
using LDT.Task.JudgetDoc.Generation.Model.DataEntity.System;
using LdtJudge.DataEngine.CallInterface;
using LdtJudge.DataEngine.CallInterface.ConfiCenter;
using LdtJudge.DataEngine.CallInterface.ConfigManager;
using LdtJudge.DataEngine.CallInterface.FileManager;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.CommonWordHandle;
using LdtJudge.DataEngine.Data.DataParseStorage;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.DataBaseStores.Cached;
using LdtJudge.DataEngine.Model.Collection;
using LdtJudge.DataEngine.Model.CommModel;
using LdtJudge.DataEngine.Model.DataModel.CommonManageModel;
using LdtJudge.DataEngine.Model.DataModel.DataParseStorage;
using LdtJudge.DataEngine.Model.DataModel.SysCommon;
using LdtJudge.DataEngine.Model.EvidenceStandardizationModel;
using LdtJudge.DataEngine.Model.OptimizationModel;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using MQModelHandleLibaryCore.Model;
using MQModelHandleLibaryCore.PublishSubscribeHandle;
using MQModelHandleLibaryCore.QueueHandle;
using MQModelHandleLibaryCore.RoutingHandle;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using static Ldt.DataEngine.LogHandle.LogHandle;

namespace LdtJudge.DataEngine.Server
{
    public class Worker : BackgroundService
    {
        private ISettingCenter settingCenter;
        private IConfigRetrieval _configRetrieval { get; set; }
        /// <summary>
        /// 实例化数据
        /// </summary>
        /// <param name="configuration">配置项</param>
        /// <param name="configRetrieval">配置中心对象</param>
        /// <param name="configManagerHandle">配置数据载体对象</param>
        public Worker(IConfiguration configuration)
        {
            configuration = new ConfigurationBuilder().SetBasePath(System.AppContext.BaseDirectory).AddJsonFile("appsettings.json", true, true).Build();
            ConfigManagerHandle configManagerHandle = new ConfigManagerHandle(configuration);
            settingCenter = (ISettingCenter)DbHelper.ServiceProvider.GetService(typeof(ISettingCenter));
            //如果没有进行配置初始化，需要进行初始化
            ConfigRetrieval callInterface = new ConfigRetrieval(configuration, configManagerHandle, settingCenter);
            _configRetrieval = callInterface;
            isdeletewordpath = configManagerHandle.IsDeleteWordPath;
            //进行配置分析服务的最大线程
            AnalysisThreadCount = configManagerHandle.AnalysisThreadCount;
            CaseOptimizeThreadCount = configManagerHandle.CaseOptimizeThreadCount;
            //获取日志输出等级配置；
            string loglevel = callInterface.GetAppSettingString("loglevel");
            //进行更新日志平台地址； 
            string logtcp = callInterface.GetAppSettingString("logstash");
            Dictionary<string, string> logConfigDic = new Dictionary<string, string>();
            logConfigDic.Add("varlogstashtcp", logtcp);
            logConfigDic.Add("varloglevel", loglevel);
            LogHandle.GetInitLogHandle.UpdateLogVar(logConfigDic);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            LogHandle.GetInitLogHandle.LogWrite("底层分析启动成功：");
        }
        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {

                Exception ex = e.ExceptionObject as Exception;
                Console.WriteLine("来自“MonitorOnServer”的全局异常。" + ex.Message + "详细信息如下："
                                    + Environment.NewLine + "［InnerException］" + ex.InnerException
                                    + Environment.NewLine + "［Source］" + ex.Source
                                    + Environment.NewLine + "［TargetSite］" + ex.TargetSite
                                    + Environment.NewLine + "［StackTrace］" + ex.StackTrace);

            }
            catch { }
        }
        /// <summary>
        /// 是否删除
        /// </summary>
        private bool isdeletewordpath = true;
        /// <summary>
        /// 设置分析的数量
        /// The thread count
        /// </summary>
        private int AnalysisThreadCount = 0;
        /// <summary>
        /// 设置案件优选数量
        /// </summary>
        private int CaseOptimizeThreadCount = 0;

        /// <summary>
        /// MQ链接对象集合
        /// key=域名；value=连接对象
        /// </summary>
        private Dictionary<string, MQModelHandleLibaryCore.Model.ConnectionConfig> connectiondic = new Dictionary<string, MQModelHandleLibaryCore.Model.ConnectionConfig>(StringComparer.OrdinalIgnoreCase);
        /// <summary>
        /// 预先定义队列的优先级参数
        /// </summary>
        internal static IDictionary<string, object> QueueArguments
        {
            get
            {
                IDictionary<string, object> arguments = new Dictionary<string, object>();
                arguments["x-max-priority"] = 10;//定义队列优先级为10个级别
                arguments["x-dead-letter-exchange"] = "DeadLetterExchange";
                arguments["x-dead-letter-routing-key"] = "DeadLetter";
                arguments.Add("x-message-ttl", 36000000);//队列上消息过期时间，应小于队列过期时间  默认为6小时
                return arguments;
            }
        }

        /// <summary>
        /// 进行管理数据分析和优选Task线程
        /// </summary>
        private static Dictionary<int, Task> taskModelList = new Dictionary<int, Task>();
        /// <summary>
        /// 用来存放实例化的消费者
        /// </summary>
        private static List<object> instantiateList = new List<object>();

        private  void LoadCommonManageData() 
        {
            Dictionary<string,object> dicTable = new Dictionary<string, object>();
            IFreeSql ManagefreeSql=CallInterface.CommHelp.FreeSQLHelp.GetFreeSQL("LdtCommonManage");
            List<ExtractInfo> extractInfoList = ManagefreeSql.Select<ExtractInfo>().ToList();
            dicTable.Add("ExtractInfo", extractInfoList);

            List<ExtractFeature> extractFeatureList = ManagefreeSql.Select<ExtractFeature>().ToList();
            dicTable.Add("ExtractFeature", extractFeatureList);

            List<ElementExtractSource> elementExtractSourceList = ManagefreeSql.Select<ElementExtractSource>().ToList();
            dicTable.Add("ElementExtractSource", elementExtractSourceList);

            List<RuleInfoUnit> ruleInfoUnitList=ManagefreeSql.Select<RuleInfoUnit>().ToList();
            dicTable.Add("RuleInfoUnit", ruleInfoUnitList);

            List<ConvertMode> convertmodeList = ManagefreeSql.Select<ConvertMode>().ToList();
            dicTable.Add("ConvertMode", convertmodeList);
            
            //IFreeSql sysfreeSql = LdtJudge.DataEngine.CallInterface.CommHelp.FreeSQLHelp.GetFreeSQL("Ldt_JudgeDocSystem");;
            //List<LdtJudge.DataEngine.Model.DataModel.SysCommon.MSYS_Express_Source> express_SourcesList = sysfreeSql.Select<LdtJudge.DataEngine.Model.DataModel.SystemtableModel.SYS_Express_Source, LdtJudge.DataEngine.Model.DataModel.SystemtableModel.SYS_Argument>().InnerJoin((a, b) => a.ES_Purpose == b.AM_ID).ToList<LdtJudge.DataEngine.Model.DataModel.SysCommon.MSYS_Express_Source>();
            //dicTable.Add("MSYS_Express_Source", express_SourcesList);

            //MsysExpressSourceCached.Initialization(express_SourcesList);

        }
        /// <summary>
        /// 执行方法
        /// </summary>
        /// <param name="stoppingToken">取消标记</param>
        /// <returns></returns>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            //实例化配置
            InitMQConfig();
            LoadCommonManageData();
            #region 注释掉数据长连接
            //广播消息对象进行初始化
            MQModelHandleLibaryCore.PublishSubscribeHandle.PublishSubscribeSend subscribeSend = new MQModelHandleLibaryCore.PublishSubscribeHandle.PublishSubscribeSend(connectiondic["CollectionAndAnalysisMQ"],
                new MQModelHandleLibaryCore.Model.ExchangeModel() { ExchangeName = "HandleProgressExchange", ExchangeDurable = true });
            instantiateList.Add(subscribeSend);
            #endregion

            //添加日志等级修改监听
            var talog = Task.Factory.StartNew(() =>
            {
                try
                {
                    //接收消息
                    RoutReceived routReceived = new RoutReceived(connectiondic["CommonPlatform"],
                        new MQModelHandleLibaryCore.Model.ExchangeModel()
                        {
                            ExchangeName = "SettingCenterDataChangedExchange",
                            ExchangeDurable = true

                        }, new MQModelHandleLibaryCore.Model.QueueModel()
                        {
                            Qdurable = true,
                            QautoDelete = false,
                            Qexclusive = false,
                            //ArgumentList = QueueArguments,
                            QueueName = "wordparseservice.queue",

                        }, new List<string>() { "wordparseapi", "logstash", "filemanager", "filecreateapi", "caseapi", "lawdatabase" });
                    routReceived.CallBackMessage = (routkey, msg) =>
                    {
                        //更新指定产品的键数据
                        _configRetrieval.UpdateAppSettingInfo(routkey.ToLower());
                        if (routkey.ToLower() == "wordparseapi")
                        {
                            string value = Convert.ToString(_configRetrieval.GetAppSettingString("loglevel"));
                            if (!string.IsNullOrWhiteSpace(value))
                            {
                                //进行更新日志信息
                                LogHandle.GetInitLogHandle.UpdateLogVar(new Dictionary<string, string>() { { "varloglevel", value } });
                                //log.Warn("接收到MQ消息，进行调整日志等级");
                            }

                        }

                    };
                    instantiateList.Add(routReceived);
                }
                catch (Exception taskMessage)
                {
                    LogHandle.GetInitLogHandle.LogWrite("初始化分析进程错误！错误消息为：" + taskMessage);
                }
            }, stoppingToken, TaskCreationOptions.LongRunning, TaskScheduler.Default).ContinueWith(val =>
            {
                val.Exception.Handle(ex =>
                {
                    Console.WriteLine("日志监听线程异常: 异常消息为： {0}", ex);
                    return true;
                });
            }, TaskContinuationOptions.OnlyOnFaulted);
            taskModelList.Add(talog.Id, talog);

            #region =========================数据提取任务============================
            for (int i = 0; i < AnalysisThreadCount; i++)
            {

                var ta = Task.Factory.StartNew(() =>
                {
                    try
                    {
                        //接收消息
                        QueueReceived queueReceived = new QueueReceived(connectiondic["CollectionAndAnalysisMQ"],
                        new MQModelHandleLibaryCore.Model.QueueModel()
                        {
                            QueueName = "TextExtractionQueue",
                            ArgumentList = QueueArguments,
                            Qdurable = true,
                            QautoDelete = false,
                            Qexclusive = false
                        });
                        queueReceived.CallBackMessage = FileExtraction;
                        instantiateList.Add(queueReceived);
                    }
                    catch (Exception taskMessage)
                    {
                        LogHandle.GetInitLogHandle.LogWrite("初始化分析进程错误！错误消息为：" + taskMessage);
                    }
                }, stoppingToken, TaskCreationOptions.LongRunning, TaskScheduler.Default).ContinueWith(val =>
                {
                    val.Exception.Handle(ex =>
                    {
                        Console.WriteLine("数据提取监听线程异常: 异常消息为： {0}", ex);
                        return true;
                    });
                }, TaskContinuationOptions.OnlyOnFaulted);
                taskModelList.Add(ta.Id, ta);
            }
            #endregion

            #region =========================数据回填任务=============================
            for (int i = 0; i < AnalysisThreadCount; i++)
            {
                try
                {
                    var ta1 = Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            //接收消息
                            QueueReceived queueReceived = new QueueReceived(connectiondic["CollectionAndAnalysisMQ"],
                                new MQModelHandleLibaryCore.Model.QueueModel()
                                {
                                    QueueName = "FillBackOptimization",
                                    ArgumentList = QueueArguments,
                                    Qdurable = true,
                                    QautoDelete = false,
                                    Qexclusive = false
                                });
                            queueReceived.CallBackMessage = FillBackOpt;
                            instantiateList.Add(queueReceived);
                        }
                        catch (Exception taskMessage)
                        {
                            LogHandle.GetInitLogHandle.LogWrite("初始化优选进程错误！错误消息为：" + taskMessage);
                        }
                    }, stoppingToken, TaskCreationOptions.LongRunning, TaskScheduler.Default).ContinueWith(val =>
                    {
                        val.Exception.Handle(ex =>
                        {
                            Console.WriteLine("案件优选监听线程异常: 异常消息为： {0}", ex);
                            return true;
                        });
                    }, TaskContinuationOptions.OnlyOnFaulted); ;
                    taskModelList.Add(ta1.Id, ta1);
                }
                catch (AggregateException ex)
                {
                    foreach (var item in ex.InnerExceptions)
                    {
                        Console.WriteLine("异常类型：{0}{1}来自：  {2} {3} 异常内容：{4} ", item.GetType(),
                    Environment.NewLine, item.Source,
                    Environment.NewLine, item.Message);
                    }
                    Console.Write(ex.Message);
                }
            }
            #endregion

            #region ===========================将任务放到任务列表中====================
            for (int i = 0; i < AnalysisThreadCount; i++)
            {
                var delectT = Task.Factory.StartNew(() =>
                {
                    try
                    {
                        //接收消息
                        QueueReceived queueReceived = new QueueReceived(connectiondic["CollectionAndAnalysisMQ"],
                         new MQModelHandleLibaryCore.Model.QueueModel()
                         {
                             QueueName = "InstrumentDeletionQueue",
                             ArgumentList = QueueArguments,
                             Qdurable = true,
                             QautoDelete = false,
                             Qexclusive = false
                         });
                        queueReceived.CallBackMessage = FilRemoveData;
                        instantiateList.Add(queueReceived);
                    }
                    catch (Exception taskMessage)
                    {
                        LogHandle.GetInitLogHandle.LogWrite("初始化优选进程错误！错误消息为：" + taskMessage);
                    }
                }, stoppingToken, TaskCreationOptions.LongRunning, TaskScheduler.Default).ContinueWith(val =>
                {
                    val.Exception.Handle(ex =>
                    {
                        Console.WriteLine("卷宗结构化数据回填监听线程异常: 异常消息为： {0}", ex);
                        return true;
                    });
                }, TaskContinuationOptions.OnlyOnFaulted);
                taskModelList.Add(delectT.Id, delectT);
            }
            #endregion

            #region =========================传入段落内容分析任务=============================
            for (int i = 0; i < AnalysisThreadCount; i++)
            {
                var paragraphT = Task.Factory.StartNew(() =>
                {
                    try
                    {
                        //接收消息
                        QueueReceived queueReceived = new QueueReceived(connectiondic["CollectionAndAnalysisMQ"],
                         new MQModelHandleLibaryCore.Model.QueueModel()
                         {
                             QueueName = "ParagraphExtractionQueue",
                             ArgumentList = QueueArguments,
                             Qdurable = true,
                             QautoDelete = false,
                             Qexclusive = false
                         });
                        queueReceived.CallBackMessage = ParagraphExtraction;
                        instantiateList.Add(queueReceived);
                    }
                    catch (Exception taskMessage)
                    {
                        LogHandle.GetInitLogHandle.LogWrite("初始化优选进程错误！错误消息为：" + taskMessage);
                    }
                }, stoppingToken, TaskCreationOptions.LongRunning, TaskScheduler.Default).ContinueWith(val =>
                {
                    val.Exception.Handle(ex =>
                    {
                        Console.WriteLine("卷宗结构化数据回填监听线程异常: 异常消息为： {0}", ex);
                        return true;
                    });
                }, TaskContinuationOptions.OnlyOnFaulted);
                taskModelList.Add(paragraphT.Id, paragraphT);
            }
            #endregion

            await Task.WhenAll(taskModelList.Select(a => a.Value));
        }

        /// <summary>
        /// 停止服务
        /// </summary>
        /// <param name="cancellationToken">取消标记</param>
        /// <returns></returns>
        public override Task StopAsync(CancellationToken cancellationToken)
        {
            //先执行停止
            base.StopAsync(cancellationToken);

            return Task.Factory.StartNew(() =>
            {
                try
                {
                    //TODO: 在此处添加代码以执行停止服务所需的关闭操作。
                    //MQMainEntrance.mQMainEntrance.Dispose();
                    //停止消费者处理
                    if (instantiateList.Count > 0)
                    {
                        for (int i = 0; i < instantiateList.Count; i++)
                        {
                            var Consumer = instantiateList[i];
                            //添加如果获取到的Dispose为空，则不执行。
                            Consumer.GetType().GetMethod("Dispose")?.Invoke(Consumer, null);
                        }
                        instantiateList.Clear();
                    }

                }
                catch (Exception ex)
                {
                    LogHandle.GetInitLogHandle.LogWrite("服务停止失败！InstantiateList结束任务失败，错误消息：" + ex.Message);
                    LogHandle.GetInitLogHandle.LogWrite("服务停止失败！InstantiateList结束任务失败，错误详细：" + ex.ToString());
                    LogHandle.GetInitLogHandle.LogWrite("服务停止失败！InstantiateList结束任务失败，错误详细：" + ex.StackTrace);
                }
                try
                {
                    if (taskModelList.Count > 0)
                    {
                        //取消执行任务;
                        for (int i = 0; i < taskModelList.Count; i++)
                        {
                            //var taskmode = TaskModelList.ToList()[i].Value;
                            var taskmode = taskModelList.Values.ToList()[i];
                            taskmode.Dispose();
                        }
                        //清除所有的线程
                        taskModelList.Clear();
                    }
                }
                catch (Exception ex)
                {
                    LogHandle.GetInitLogHandle.LogWrite("服务停止失败！TaskModelList任务结束时错误，错误消息：" + ex.Message);
                    LogHandle.GetInitLogHandle.LogWrite("服务停止失败！TaskModelList任务结束时错误，错误详细：" + ex.ToString());
                    LogHandle.GetInitLogHandle.LogWrite("服务停止失败！TaskModelList任务结束时错误，错误详细：" + ex.StackTrace);
                }


            });

        }
        /// <summary>
        /// 进行初始化系统MQ配置
        /// </summary>
        private void InitMQConfig()
        {
            //调用配置中心，进行获取数据分析队列的MQ地址
            string connstr = _configRetrieval.GetConnectionString("CollectionAndAnalysisMQ");
            var attrib = connstr.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < attrib.Length; i++)
            {
                attrib[i] = attrib[i].Substring(attrib[i].IndexOf("=") + 1);
            }
            var hostname = attrib[0].Split(':');
            //进行实例化MQ通讯对象
            var connection = new MQModelHandleLibaryCore.Model.ConnectionConfig()
            {
                Hostname = hostname[0],
                Port = Convert.ToInt32(hostname[1]),
                Pwssword = attrib[3],
                Username = attrib[2],
                Virtualhost = attrib[1],
                AutomaticRecoveryEnabled = true//2019-06-05ljx 启用断线自动重连
            };
#if DEBUG
            connection = new ConnectionConfig()
            {
                Hostname = "192.168.1.130",
                Port = Convert.ToInt32("5672"),
                Pwssword = "admin",
                Username = "admin",
                Virtualhost = "CollectionAndWordParseVHost",
                AutomaticRecoveryEnabled = true
            };
#endif
            connectiondic.Add("CollectionAndAnalysisMQ", connection);

            //获取通用交互域
            string commconnstr = _configRetrieval.GetConnectionString("CommonPlatform");
            var attribt = commconnstr.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < attribt.Length; i++)
            {
                attribt[i] = attribt[i].Substring(attribt[i].IndexOf("=") + 1);
            }
            string[] hostnamet = attribt[0].Split(':');
            //进行实例化MQ通讯对象
            var connectiont = new MQModelHandleLibaryCore.Model.ConnectionConfig()
            {
                Hostname = hostnamet[0],
                Port = Convert.ToInt32(hostnamet[1]),
                Pwssword = attribt[3],
                Username = attribt[2],
                Virtualhost = attribt[1],
                AutomaticRecoveryEnabled = true//2019-06-05ljx 启用断线自动重连
            };
            connectiondic.Add("CommonPlatform", connectiont);


        }


        #region 委托实现，接收到MQ消息后进行处理
        /// <summary>
        /// 文本提取接口
        /// </summary>
        /// <param name="message">接收到的消息内容</param>
        public void FileExtraction(string message)
        {

            string state = "1";
            FileExtractModel fileExtractModel = JsonConvert.DeserializeObject<FileExtractModel>(message.Replace("&#x13;", "").Replace("&#x14;", "").Replace("&#x15;", "").Replace("&#xD;", ""));
            fileExtractModel.MsgState = "0";
            LogHandle.GetInitLogHandle.LogWrite("文书分析参数为：" + message);
            try
            {
              

                //交互实体
                BufferModel bufferModel = new BufferModel();
                List<DocInfol> DocInfolList = new List<DocInfol>();
                
                DocInfolList.AddRange(fileExtractModel.DocInfos.Where(a => a.SourceCode.ToLower() == "mssuitbook").ToList());
                DocInfolList.AddRange(fileExtractModel.DocInfos.Where(a => a.SourceCode.ToLower() == "ws010003614").ToList());
                DocInfolList.AddRange(fileExtractModel.DocInfos.Where(a => a.SourceCode.ToLower() == "ws010000050").ToList());
                DocInfolList.AddRange(fileExtractModel.DocInfos.Where(a => a.SourceCode.ToLower() == "ws0100011427").ToList());
                DocInfolList.AddRange(fileExtractModel.DocInfos.Where(a => a.SourceCode.ToLower() == "ws010000776").ToList());
                DocInfolList.AddRange(fileExtractModel.DocInfos.Where(a => a.SourceCode.ToLower() == "ws0100015457").ToList());
                DocInfolList.AddRange(fileExtractModel.DocInfos.Where(a => a.SourceCode.ToLower() == "xssuitbook").ToList());
                DocInfolList.AddRange(fileExtractModel.DocInfos.Where(a => a.SourceCode.ToLower() == "xzsuitbook").ToList());
                if (fileExtractModel.DocInfos.FirstOrDefault(a => a.SourceCode != "mssuitbook" && a.SourceCode != "xssuitbook" && a.SourceCode != "xzsuitbook" && a.SourceCode.ToLower() != "ws010003614" && a.SourceCode.ToLower() != "ws010000050" && a.SourceCode.ToLower() != "ws0100011427" && a.SourceCode.ToLower() != "ws010000776" && a.SourceCode.ToLower() != "ws0100015457") != null)
                {
                    foreach (DocInfol infol in fileExtractModel.DocInfos.Where(a => a.SourceCode.ToLower() != "mssuitbook" && a.SourceCode.ToLower() != "xssuitbook" && a.SourceCode.ToLower() != "xzsuitbook" && a.SourceCode.ToLower() != "ws010003614" && a.SourceCode.ToLower() != "ws010000050" && a.SourceCode.ToLower() != "ws0100011427" && a.SourceCode.ToLower() != "ws010000776" && a.SourceCode.ToLower() != "ws0100015457").ToList())
                    {
                        DocInfolList.Add(infol);
                    }
                }
                for (int i = 0; i < DocInfolList.Count; i++)
                {
                    DocInfol docInfol = DocInfolList[i];
                    try
                    { 
                        #region 文书循环分析优选
                        string docPath = docInfol.FileUrl;

                        bufferModel.OutRelatID = fileExtractModel.CaseInfo.OutRealtId;
                        bufferModel.SourceName = docInfol.SourceCode;
                        bufferModel.MsgId = fileExtractModel.MsgId;
                        bufferModel.HandleType = "1";
                        bufferModel.FilePath = docInfol.FileUrl;
                        bufferModel.SourceCode = docInfol.SourceCode;
                        bufferModel.SourceID = docInfol.SFID;
                      
                        System.Runtime.CallContext.SetData("systemplatform", ConfigManagerHandle.PlatFormName.wordparse_analysisservice);
                        System.Runtime.CallContext.SetData("baseDirectory", _configRetrieval.GetLogPath());
                        System.Runtime.CallContext.SetData("identifier", bufferModel.OutRelatID.ToLower());//当前案件唯一ID
                        System.Runtime.CallContext.SetData("typename", bufferModel.SourceCode.ToLower());//当前分析的文书名称
                        System.Runtime.CallContext.SetData("customid", fileExtractModel.MsgId);//当前标识ID
                        WordHandle wordHandle = new WordHandle();
                        string content = "";
                        if (!string.IsNullOrEmpty(docPath))
                        {
                            try
                            {
                                LogHandle.GetInitLogHandle.LogWrite("获取文件流路径：" + docPath);
                                content = wordHandle.GerBysetWrodContext(docPath);
                                LogHandle.GetInitLogHandle.LogWrite("获取文件内容：" + content);
                            }
                            catch (Exception exf)
                            {

                                LogHandle.GetInitLogHandle.LogWrite("文件流获取文本错误：" + exf.ToString());
                                throw;
                            }
                        }
                        else
                        {
                            LogHandle.GetInitLogHandle.LogWrite("获取文件流路径为空！！！");
                        }
                        if (!string.IsNullOrEmpty(content))
                        {
                            RealizationClass realizationClass = new RealizationClass();
                            realizationClass.Connection = connectiondic["CollectionAndAnalysisMQ"];
                            string district = fileExtractModel.District ?? _configRetrieval.GetAppSettingString("district");
                            MainInputParameterModel inputParameter = new MainInputParameterModel()
                            {
                                CaseType = fileExtractModel.CaseInfo.CaseType,
                                DocID = bufferModel.SourceCode,
                                SourceContent = content,
                                SD_CaseOnlyID = bufferModel.OutRelatID,
                                FilePath = "",
                                CaseCause = fileExtractModel.CaseInfo.CaseCause,
                                CourtId = "",
                                AppId = "",
                                CaseID = fileExtractModel.CaseInfo.CaseId,
                                FL_ID = docInfol.FileId,
                                SF_ID = docInfol.SFID,
                                laststage = fileExtractModel.laststage,
                                BCXml= docInfol.BackXml,
                                IsSave = true,
                                District=district
                            };
                            ConfigFlowLoad configFlowLoad = new ConfigFlowLoad();
                            Ldt.DataEngin.Assemble.MainComponentBase main = new Ldt.DataEngin.Assemble.MainComponentBase(configFlowLoad);
                            main.inputParameter = inputParameter;

                            main.LogShow = new LogShow(realizationClass.LogShow);
                            main.ProcessShow = new ProcessShow(realizationClass.ProcessShow);
                            main.ModuleProcessShow = new ModuleProcessShow(realizationClass.ModularModelSet);

                            // 执行分析
                            main.GetFlowConfig(ConfigFlowLoad.FlowType.Ana);
                            main.ExtractWrap();
                            docInfol.MsgState = "1";
                            docInfol.Version = 2.0;
                            docInfol.CaseType = fileExtractModel.CaseInfo.CaseType;
                            docInfol.CaseID = fileExtractModel.CaseInfo.CaseId;
                            LogHandle.GetInitLogHandle.LogWrite("发送文件广播:" + ConfigManagerHandle.ReturnJsonString(docInfol));
                            MQModelHandleLibaryCore.PublishSubscribeHandle.PublishSubscribeSend.PublishMessageShort(connectiondic["CollectionAndAnalysisMQ"], new ExchangeModel() { ExchangeName = "PubExtractionFinished", ExchangeDurable = true }, "fin", ConfigManagerHandle.ReturnJsonString(docInfol), 5);
                        }
                        #endregion
                    }
                    catch (Exception e)
                    {
                        docInfol.MsgState = "0";
                        docInfol.ErrMessage = e.Message.ToString();
                        LogHandle.GetInitLogHandle.LogWrite("发送文件广播:" + ConfigManagerHandle.ReturnJsonString(docInfol));
                        MQModelHandleLibaryCore.PublishSubscribeHandle.PublishSubscribeSend.PublishMessageShort(connectiondic["CollectionAndAnalysisMQ"], new ExchangeModel() { ExchangeName = "PubExtractionFinished", ExchangeDurable = true }, "fin", ConfigManagerHandle.ReturnJsonString(docInfol), 5);

                    }
                }
            }
            catch (Exception e)
            {
                state = "0";
                LogHandle.GetInitLogHandle.LogWrite("分析完成失败：错误消息内容为：" + e.Message);
                LogHandle.GetInitLogHandle.LogWrite("分析完成失败：错误消息内容为：" + e.StackTrace);
                LogHandle.GetInitLogHandle.LogWrite("分析完成失败：TextExtractionFinishedQueue发送消息内容为：" + message);
            }
            finally
            {
                //错误消息内容
                string errormsg = string.Empty;
                try
                {
                    //返回错误信息
                    FileExtractModel fileExtractModels = ConfigManagerHandle.ReturnJsonToModel<FileExtractModel>(message);
                    fileExtractModel.MsgTypeName = "FileOptimize";
                    fileExtractModel.MsgState = state;

                    string strmsg = ConfigManagerHandle.ReturnJsonString(fileExtractModel);

                    //QueueSend queueSend = new QueueSend(connectiondic["CollectionAndAnalysisMQ"], new MQModelHandleLibaryCore.Model.QueueModel()
                    //{
                    //    QueueName = "DataChoiceFinishedQueue",
                    //    QautoDelete = false,
                    //    Qdurable = true,
                    //    Qexclusive = false,
                    //    ArgumentList = QueueArguments
                    //});
                    //queueSend.SendMessageStandard(strmsg);

                    MQModelHandleLibaryCore.QueueHandle.QueueSend.SendMessageShortStandard(connectiondic["CollectionAndAnalysisMQ"], new QueueModel()
                    {
                        QueueName = "DataChoiceFinishedQueue",
                        QautoDelete = false,
                        Qdurable = true,
                        Qexclusive = false,
                        ArgumentList = QueueArguments
                    }, strmsg,255);
                    

                    //MQModelHandleLibaryCore.PublishSubscribeHandle.PublishSubscribeSend.PublishMessageShort(connectiondic["CollectionAndAnalysisMQ"], new ExchangeModel() { ExchangeName = "PubExtractionFinished", ExchangeDurable = true }, "fin", strmsg, 5);

                    //LogHandle.GetInitLogHandle.LogWrite("分析完成：TextExtractionFinishedQueue发送消息内容为：" + strmsg);
                }
                catch (Exception exs)
                {
                    errormsg += exs.Message;
                }
                if (!string.IsNullOrWhiteSpace(errormsg))
                {
                    LogHandle.GetInitLogHandle.LogWrite("分析完成错误：消息内容为：" + errormsg);
                }

            }

        }


        /// <summary>
        /// 卷宗证据回填接口
        /// </summary>
        /// <param name="message">从MQ获取到的数据</param>
        public void EvidenceFillBack(string message)
        {
            // 2.业务处理并返回处理到完成队列
            string state = "1";
            try
            {
                // 交互实体(包含案件ID，以及一个证据list)
                EvidenceFillBackModel caseEvidenceInfo = ConfigManagerHandle.ReturnJsonToModel<EvidenceFillBackModel>(message.Replace("&#x13;", "").Replace("&#x14;", "").Replace("&#x15;", "").Replace("&#xD;", ""));
                LogHandle.GetInitLogHandle.LogWrite(LogHandle.LogHType.Warn, "开始卷宗证据回填：收到消息内容为：" + message.Replace("&#x13;", "").Replace("&#x14;", "").Replace("&#x15;", "").Replace("&#xD;", ""));
                IConfiguration configuration = new ConfigurationBuilder().SetBasePath(System.AppContext.BaseDirectory).AddJsonFile("appsettings.json", true, true).Build();
                ConfigManagerHandle configManagerHandle = new ConfigManagerHandle(configuration);
                //如果没有进行配置初始化，需要进行初始化
                ConfigRetrieval callInterface = new ConfigRetrieval(configuration, configManagerHandle, settingCenter);
                _configRetrieval = callInterface;
                isdeletewordpath = Convert.ToBoolean(configuration["appSettings:IsDeleteWordPath"]);
                // 交互实体(包含案件ID，以及一个证据list)

                RealizationClass realizationClass = new RealizationClass();

                Ldt.DataEngin.Assemble.Main main = new Ldt.DataEngin.Assemble.Main();
                main.configRetrieval = _configRetrieval;
                main.Loading(caseEvidenceInfo.CaseInfo.CaseType, "", caseEvidenceInfo.CaseInfo.OutRealtId, "", "", caseEvidenceInfo.CaseInfo.CaseCause, caseEvidenceInfo.CaseInfo.CaseId);
                main.EvidenceBackfill(caseEvidenceInfo);

                System.Runtime.CallContext.SetData("systemplatform", ConfigManagerHandle.PlatFormName.wordparse_analysisservice);
                System.Runtime.CallContext.SetData("baseDirectory", _configRetrieval.GetLogPath());
                System.Runtime.CallContext.SetData("identifier", caseEvidenceInfo.MsgId);//当前案件唯一ID
                System.Runtime.CallContext.SetData("typename", "evidencefillback");//当前分析的文书名称
                System.Runtime.CallContext.SetData("customid", Thread.CurrentThread.ManagedThreadId.ToString());//当前标识ID

                #region 通过MQ返回回填结果
                // 将回填结果转成json数据
                string strmsg = ConfigManagerHandle.ReturnJsonString(caseEvidenceInfo);

                QueueSend queueSend = new QueueSend(connectiondic["CollectionAndAnalysisMQ"], new MQModelHandleLibaryCore.Model.QueueModel()
                {
                    QueueName = "DataChoiceFinishedQueue",
                    QautoDelete = false,
                    Qdurable = true,
                    Qexclusive = false,
                    ArgumentList = QueueArguments
                });
                queueSend.SendMessage(strmsg);

                #endregion

                LogHandle.GetInitLogHandle.LogWrite("卷宗证据回填完成：发送消息内容为：" + strmsg);
            }
            catch (Exception ex)
            {
                state = "0";
                LogHandle.GetInitLogHandle.LogWrite("卷宗证据回填完成，但失败：错误消息内容为：" + ex.Message);
                LogHandle.GetInitLogHandle.LogWrite("卷宗证据回填完成，但失败：错误消息内容为：" + ex.StackTrace);
            }
            finally
            {
                string errormsg = string.Empty;
                try
                {
                    EvidenceFillBackModel caseEvidenceInfo = ConfigManagerHandle.ReturnJsonToModel<EvidenceFillBackModel>(message);
                    FileExtractModel fileExtractModel = new FileExtractModel();
                    fileExtractModel.MsgTypeName = "DossierDataBackfillingQueue";
                    fileExtractModel.MsgState = state;
                    fileExtractModel.MsgId = caseEvidenceInfo.MsgId;
                    if (caseEvidenceInfo.CaseInfo != null)
                        fileExtractModel.CaseInfo = new Model.Collection.CaseInfo()
                        {
                            CaseCause = caseEvidenceInfo.CaseInfo?.CaseCause,
                            CaseCode = caseEvidenceInfo.CaseInfo?.CaseCode,
                            CaseId = caseEvidenceInfo.CaseInfo?.CaseId,
                            CaseType = caseEvidenceInfo.CaseInfo?.CaseType,
                            OutRealtId = caseEvidenceInfo.CaseInfo?.OutRealtId

                        };
                    fileExtractModel.DocInfos = new List<DocInfol>();
                    foreach (var dossier in caseEvidenceInfo.PersonDossier[0].DossierList)
                    {
                        fileExtractModel.DocInfos.Add(new DocInfol()
                        {
                            FileId = "",
                            SFID = dossier.SBPID,
                            SourceCode = dossier.DossierCode,
                        });
                    }

                    QueueSend queueSend = new QueueSend(connectiondic["CollectionAndAnalysisMQ"], new MQModelHandleLibaryCore.Model.QueueModel()
                    {
                        QueueName = "DataChoiceFinishedQueue",
                        QautoDelete = false,
                        Qdurable = true,
                        Qexclusive = false,
                        ArgumentList = QueueArguments
                    });
                    queueSend.SendMessage(ConfigManagerHandle.ReturnJsonString(fileExtractModel));
                  
                }
                catch (Exception exs)
                {
                    errormsg += exs.Message;
                }
                if (!string.IsNullOrWhiteSpace(errormsg))
                {
                    LogHandle.GetInitLogHandle.LogWrite("卷宗证据回填完成，但失败：错误消息内容为：" + errormsg);
                }

            }
        }


        /// <summary>
        /// 管辖案件数据回填优选
        /// </summary>
        /// <param name="">从MQ获取到的数据</param>
        public void FillBackOpt(string message)
        {

            string state = "1";
            Dictionary<string, object> dicValue = new Dictionary<string, object>();

            //交互实体
            try
            {
                FileExtractModel fileExtractModel = new FileExtractModel();

                FillBackOptParameterModel fillBackOptParameter = JsonConvert.DeserializeObject<FillBackOptParameterModel>(message.Replace("&#x13;", "").Replace("&#x14;", "").Replace("&#x15;", "").Replace("&#xD;", ""));
                System.Runtime.CallContext.SetData("systemplatform", ConfigManagerHandle.PlatFormName.wordparse_analysisservice);
                System.Runtime.CallContext.SetData("baseDirectory", _configRetrieval.GetLogPath());
                System.Runtime.CallContext.SetData("identifier", fillBackOptParameter.Outrelatid);//当前案件唯一ID
                System.Runtime.CallContext.SetData("typename", "backfill");//当前分析的文书名称
                System.Runtime.CallContext.SetData("customid", fileExtractModel.MsgId);//当前标识ID
                LogHandle.GetInitLogHandle.LogWrite(LogHType.Warn,"管辖案件数据回填  收到MQ消息：" + message);
                fileExtractModel.MsgId = fillBackOptParameter.MsgId;
                fileExtractModel.CaseInfo = new Model.Collection.CaseInfo();
                fileExtractModel.CaseInfo.OutRealtId = fillBackOptParameter.Outrelatid;
                fileExtractModel.CaseInfo.CaseId = fillBackOptParameter.CaseID;
                try
                {
                    RealizationClass realizationClass = new RealizationClass();
                    realizationClass.Connection = connectiondic["CollectionAndAnalysisMQ"];
                    if (fillBackOptParameter.Contents!=null  && fillBackOptParameter.Contents.Count>0)
                    {

                        Ldt.DataEngin.Assemble.Main main = new Ldt.DataEngin.Assemble.Main();
                        main.configRetrieval = _configRetrieval;
                        main.ProcessShow = new ProcessShow(realizationClass.ProcessShow);
                        main.ModuleProcessShow = new ModuleProcessShow(realizationClass.SetModuleProcess);
                        main.configRetrieval = _configRetrieval;
                        main.FillBackOptimization(fillBackOptParameter);
                        fileExtractModel.MsgState = "1";
                    }
                }
                catch (Exception ex)
                {
                    fileExtractModel.MsgState = "0";
                    state = "0";
                    dicValue.Add("CaseID", fillBackOptParameter.CaseID);
                    dicValue.Add("OutRelateId", fillBackOptParameter.Outrelatid);
                    dicValue.Add("CaseTypeId", fillBackOptParameter.CaseType);
                    dicValue.Add("State", state);
                    dicValue.Add("MsgId", fillBackOptParameter.MsgId);
                    fillBackOptParameter.MsgState = "0";
                    LogHandle.GetInitLogHandle.LogWrite("分析失败：" + JsonConvert.SerializeObject(ex));
                }
                finally
                {
                    MQModelHandleLibaryCore.QueueHandle.QueueSend.SendMessageShortStandard(connectiondic["CollectionAndAnalysisMQ"], new QueueModel()
                    {
                        QueueName = "DataChoiceFinishedQueue",
                        QautoDelete = false,
                        Qdurable = true,
                        Qexclusive = false,
                        ArgumentList = QueueArguments
                    }, JsonConvert.SerializeObject(fileExtractModel), 255);

                }
            }
            catch (Exception ex)
            {
                LogHandle.GetInitLogHandle.LogWrite("消息转换实体失败：" + message);

                LogHandle.GetInitLogHandle.LogWrite("消息转换实体失败：" + JsonConvert.SerializeObject(ex)); 
            }

        }

        /// <summary>
        /// 删除数据源
        /// </summary>
        /// <param name="message">从MQ获取的数据</param>
        public void FilRemoveData(string message)
        {
            LogHandle.GetInitLogHandle.LogWrite("删除指定数据源,收到MQ消息：" + message);
            //交互实体
            DataSourceRemoveModel removeModel = new DataSourceRemoveModel();
            try
            {
                removeModel = JsonConvert.DeserializeObject<DataSourceRemoveModel>(message);
                RealizationClass realizationClass = new RealizationClass();
                if(removeModel.DocInfos!=null && removeModel.DocInfos.Any())
                {
                    string caseTypeCode = string.Empty;
                    foreach (var item in removeModel.DocInfos)
                    {
                        try
                        {
                            string msgState = string.Empty;
                            string errMsg = string.Empty;
                            Ldt.DataEngin.Assemble.Main main = new Ldt.DataEngin.Assemble.Main();
                            main.LogShow = new LogShow(realizationClass.LogShow);
                            main.ProcessShow = new ProcessShow(realizationClass.ProcessShow);
                            main.ModuleProcessShow = new ModuleProcessShow(realizationClass.SetModuleProcess);
                            main.InstrumentDeletion(removeModel.CaseInfo?.CaseType, removeModel.CaseInfo?.CaseId, item.SourceCode,out msgState,out errMsg);
                            item.MsgState = msgState;
                            item.ErrMessage = errMsg;
                        }
                        catch (Exception ex)
                        {
                            item.MsgState = "0";
                            item.ErrMessage = ex.ToString();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHandle.GetInitLogHandle.LogWrite(LogHType.Error,$"执行指定数据源删除失败：{ex.ToString()}");
            }
            finally
            {
                try
                {
                    QueueSend queueSend = new QueueSend(connectiondic["CollectionAndAnalysisMQ"], new MQModelHandleLibaryCore.Model.QueueModel()
                    {
                        QueueName = "DataChoiceFinishedQueue",
                        QautoDelete = false,
                        Qdurable = true,
                        Qexclusive = false,
                        ArgumentList = QueueArguments
                    });
                    LogHandle.GetInitLogHandle.LogWrite(LogHType.Info, $"执行指定数据源删除完成结果：{JsonConvert.SerializeObject(removeModel)}");
                    queueSend.SendMessage(JsonConvert.SerializeObject(removeModel));
                    LogHandle.GetInitLogHandle.LogWrite("执行删除指定数据源完成，发送广播完成");
                }
                catch (Exception exs)
                {
                    LogHandle.GetInitLogHandle.LogWrite(LogHType.Error,$"执行删除指定数据源完成，发送广播失败，{exs.ToString()}");
                }
            }
        }

        /// <summary>
        /// 段落单独分析
        /// </summary>
        /// <param name="message"></param>
        public void ParagraphExtraction(string message)
        {
            try
            {
                ParagraphExtractModel paragraphExtractModel = JsonConvert.DeserializeObject<ParagraphExtractModel>(message);
                paragraphExtractModel.MsgTypeName = "paragraphextractionqueue";
                System.Runtime.CallContext.SetData("systemplatform", ConfigManagerHandle.PlatFormName.wordparse_analysisservice);
                System.Runtime.CallContext.SetData("baseDirectory", _configRetrieval.GetLogPath());
                System.Runtime.CallContext.SetData("identifier", paragraphExtractModel.OutRealtId);//当前案件唯一ID
                System.Runtime.CallContext.SetData("typename", "paragraphextract");//当前分析的文书名称
                System.Runtime.CallContext.SetData("customid", paragraphExtractModel.MsgId);//当前标识ID
                LogHandle.GetInitLogHandle.LogWrite(LogHType.Warn, "段落单独分析 收到MQ消息：" + message);
                try
                {
                    RealizationClass realizationClass = new RealizationClass();
                    realizationClass.Connection = connectiondic["CollectionAndAnalysisMQ"];
                    string district = paragraphExtractModel.District ?? _configRetrieval.GetAppSettingString("district");
                    MainInputParameterModel inputParameter = new MainInputParameterModel()
                    {
                        CaseType = paragraphExtractModel.CaseType,
                        DocID = paragraphExtractModel.SourceCode,
                        SD_CaseOnlyID = paragraphExtractModel.OutRealtId,
                        FilePath = "",
                        CaseCause = paragraphExtractModel.CaseCause,
                         CourtId = "",
                        AppId = paragraphExtractModel.AppId,
                        CaseID = paragraphExtractModel.CaseId,
                        laststage = paragraphExtractModel.laststage,
                        IsSave = true,
                        District = paragraphExtractModel.District,
                        BCXml = paragraphExtractModel.BackXml,
                        IsParagraphAnalysis = true,
                        ParagraphModels = paragraphExtractModel.Paragraphs
                    };
                    ConfigFlowLoad configFlowLoad = new ConfigFlowLoad();
                    Ldt.DataEngin.Assemble.MainComponentBase main = new Ldt.DataEngin.Assemble.MainComponentBase(configFlowLoad);
                    main.inputParameter = inputParameter;

                    main.LogShow = new LogShow(realizationClass.LogShow);
                    main.ProcessShow = new ProcessShow(realizationClass.ProcessShow);
                    main.ModuleProcessShow = new ModuleProcessShow(realizationClass.ModularModelSet);

                    // 执行分析
                    main.GetFlowConfig(ConfigFlowLoad.FlowType.Ana);
                    if (inputParameter.IsParagraphAnalysis == true)
                    {
                        main.configmodels = main.configmodels.Where(x => !x.Code.ToLower().Contains("moudletextformattingextract") && !x.Code.ToLower().Contains("moudleparagraphextract")).ToList();
                    }
                    main.ExtractWrap();
                    paragraphExtractModel.MsgState = "1";
                }
                catch (Exception ex)
                {
                    paragraphExtractModel.MsgState = "0";
                    paragraphExtractModel.ErrMessage = ex.ToString();
                    LogHandle.GetInitLogHandle.LogWrite("段落单独分析失败：" + JsonConvert.SerializeObject(ex));
                }
                finally
                {
                    string finishMsg = ConfigManagerHandle.ReturnJsonString(paragraphExtractModel);
                    MQModelHandleLibaryCore.QueueHandle.QueueSend.SendMessageShortStandard(connectiondic["CollectionAndAnalysisMQ"], new QueueModel()
                    {
                        QueueName = "DataChoiceFinishedQueue",
                        QautoDelete = false,
                        Qdurable = true,
                        Qexclusive = false,
                        ArgumentList = QueueArguments
                    }, finishMsg, 255);
                    MQModelHandleLibaryCore.PublishSubscribeHandle.PublishSubscribeSend.PublishMessageShort(connectiondic["CollectionAndAnalysisMQ"], new ExchangeModel() { ExchangeName = "PubExtractionFinished", ExchangeDurable = true }, "fin", finishMsg, 5);
                    LogHandle.GetInitLogHandle.LogWrite($"段落单独分析完成：PubExtractionFinished发送消息内容为：{finishMsg}");

                }
            }
            catch (Exception ex)
            {
                LogHandle.GetInitLogHandle.LogWrite("段落单独分析，消息转换实体失败：" + message);
                LogHandle.GetInitLogHandle.LogWrite("段落单独分析，消息转换实体失败：" + JsonConvert.SerializeObject(ex));
            }
           
        }

        #endregion
    }
}
